#!/usr/bin/perl
use strict;

package csopme;
use modules::encode;
sub csopme {
    my ($dbh,$remote,$input,$csnum)=@_;
    my $sth;
    $sth = $dbh->prepare("SELECT num,auth,nick FROM ninfo WHERE num = '$$input[0]';");
    $sth->execute;
    my ($auth,$nick);
    while (my @tmp = $sth->fetchrow_array) {
	if ($tmp[0] eq $$input[0]) {
	    $auth = $tmp[1];
	    $nick = $tmp[2];
	}
    }
    if ($auth eq '0') {
	print $remote "$csnum O $$input[0] :You have to identify with nickserv in order to use this command.\n";
    }
    elsif ($$input[4] ne "") {
	$sth=$dbh->prepare("SELECT channel FROM onchan WHERE code = '" . encode::encode($$input[0]) . "' AND num = '$$input[0]' AND channel = '$$input[4]';");
	$sth->execute;
	my $true = $sth->fetchrow_array;

	$sth=$dbh->prepare("SELECT auth FROM ninfo WHERE num = '$$input[0]' AND code = '".encode::encode($$input[0])."';");
	$sth->execute;
	my $auth = $sth->fetchrow_array;
	if (!($true)) {
	    print $remote "$csnum O $$input[0] :You have to be on $$input[4] and not opped.\n";
	}
	elsif (isaccess($$input[4],$dbh,$auth)) {
	    print $remote "$csnum M $$input[4] +o $$input[0]\n";
	    $sth=$dbh->prepare("UPDATE onchan SET isop = '1' WHERE num = '$$input[0]' AND code = '".encode::encode($$input[0])."' AND channel = '$$input[4]';");
	    $sth->execute;
	    print $remote "$csnum O $$input[0] :Gave you ops on $$input[4].\n";
	}
	else {
	    print $remote "$csnum O $$input[0] :Access denied\n";
	}
	}


    else {
	my $count = 0;
	my $encode = encode::encode($$input[0]);
	my $sth=$dbh->prepare("SELECT channel FROM onchan WHERE code = '$encode' AND num = '$$input[0]' AND isop = '0';");
	$sth->execute();
	my @channels;
	while (my $i = $sth->fetchrow_array) {
	    push @channels, $i;
	    undef $i;
	}
	
	foreach my $i (@channels) {
 
		if (&isaccess($i,$dbh,$auth)) {
		    print $remote "$csnum M $i +o $$input[0]\n";
		    $count++;
		    $sth=$dbh->prepare("UPDATE onchan SET isop = '1' WHERE code = '".encode::encode($$input[0])."' AND num = '$$input[0]' AND channel = '$i';");
		    $sth->execute;
		}

	}
	undef @channels;
       
    
	print $remote "$csnum O $$input[0] :Gave you ops on (\cB$count\cB) channel(s).\n";
    }
}

sub isaccess {
    my ($channel,$dbh,$auth) = @_;
    my $sth = $dbh->prepare("SELECT level FROM users WHERE channel = '$channel' AND rnick = '$auth';");
    $sth->execute;
    my $yes = $sth->fetchrow_array;
    if ($yes > 99) {
	return 1;
    }
    else {
	return 0;
    }
}
1;
